import wiringpi as gpio


gpio.wiringPiSetupPhys()
gpio.ds1302setup(11, 12, 13)

gpio.ds1302rtcWrite(0, 0x80)

def rtcRead():
  seconds = gpio.ds1302rtcRead(0)
  ch = seconds >> 7
  if ch == 1:
    print('DS1302 ERROR')
    return
  second = ((seconds >> 4) & 0x7)*10 + (seconds & 0xf)
  print("Second: {}".format(second))
  minutes = gpio.ds1302rtcRead(1)
  minute = ((minutes >> 4)&0x7)*10+(minutes&0xf)
  print("Minute: {}".format(minute))
  hours = gpio.ds1302rtcRead(2)
  is24Hour = (hours >> 7) == 0
  hour = 0
  isAM = False
  if is24Hour:
    hour = (hours >> 4 & 0x3)*10 + (hours & 0xf)
  else:
    isAM = hours >> 5 & 0x1 == 0
    hour = 'AM' if isAM else 'PM' + str((hours >> 4 & 0x1)*10 + (hours & 0xf))
  print("Hour: {}".format(hour))
  dates = gpio.ds1302rtcRead(3)
  date = (dates>>4&0x3)*10 + (dates&0xf)
  print('Date: {}'.format(date))
  months = gpio.ds1302rtcRead(4)
  month = (months>>4&0x1)*10+(months&0xf)
  print('Month: {}'.format(month))
  weeks = gpio.ds1302rtcRead(5)
  print('Week: {}'.format(weeks))
  years = gpio.ds1302rtcRead(6)
  year = (years >> 4 & 0xf)*10+(years&0xf)
  print('Year: {}'.format(year))
  print(gpio.ds1302rtcRead(7))

if __name__ == '__main__':
  rtcRead()
